#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define SERVER_IP "127.0.0.1"
#define PORT 12345
#define MAX_BUFFER 1024

int main() {
    int sock;
    struct sockaddr_in server_addr;
    char buffer[MAX_BUFFER];

    // 创建socket
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("无法创建socket");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        perror("无效的地址");
        close(sock);
        exit(EXIT_FAILURE);
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("连接失败");
        close(sock);
        exit(EXIT_FAILURE);
    }

    printf("连接到服务器成功\n");

    // 与服务器交互
    while (1) {
        printf("请输入英文或中文单词（输入 'exit' 退出）：");
        fgets(buffer, MAX_BUFFER, stdin);
        buffer[strcspn(buffer, "\n")] = '\0';

        if (strcmp(buffer, "exit") == 0) {
            break;
        }

        send(sock, buffer, strlen(buffer), 0);
        memset(buffer, 0, MAX_BUFFER);
        int bytes_received = recv(sock, buffer, MAX_BUFFER, 0);
        if (bytes_received > 0) {
            printf("翻译结果：%s\n", buffer);
        }
    }

    printf("断开与服务器的连接\n");
    close(sock);
    return 0;
}
